package com.mojo.concurrent.threadsafe;

/**
 * 线程yield方法使用示例
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/19 9:52
 */
public class ThreadYield {
    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        Thread t = new Thread(myThread);
        t.start();
        t.join(5000);
        System.out.println("主线程。。。。");
    }
}

class MyThread implements Runnable {
    @Override
    public void run() {
        while (true) {

            try {
                Thread.sleep(1000);
                //yield 放弃、屈服，在线程中标识让步于同优先级的线程，线程由运行状态转为就绪状态，再由OS调度；放弃CPU时间片，但不释放锁资源
                Thread.yield();
                int i = 1 / 0;
            } catch (Exception e) {
                e.printStackTrace();
                Thread.yield();
            }
        }
    }
}